package suanfa.datastructure.stack;

public class LinkStack<T> {
     class Node{
        public int data;
        public Node next;

        public Node(int data){
            this.next=null;
            this.data=data;
        }
    }
    public int size=0;
    public Node top;



    public int getSize(){
        return size;
    }
    public boolean isEmpty(){//判空方法
        return top==null;
    }
    public void push(int data){//入栈
        Node newnode=new Node(data);//临时结点
        if(isEmpty()){//判空
            top=newnode;
        }
        else{
            newnode.next=top;
            top=newnode;
            size++;
        }

    }

    public int pop(){//出栈
        if(isEmpty()){
            throw new IllegalStateException("栈已空");
        }else{
            int t=top.data;//存栈顶元素
            top=top.next;//移动top指针
            return t;
        }
    }

    public int peek(){//返回栈顶元素
        if(isEmpty()){
            throw new IllegalStateException("栈已空");
        }else{
            return top.data;
        }
    }
    public static void main(String[] args) {
        LinkStack<Integer> s=new LinkStack<>();
        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println("栈顶元素为："+s.peek());
        for(int i=0;i<=s.size;i++){
            System.out.println("pop-> "+s.pop());
        }

    }
}
